$(document).ready(function(){
    var ty_mutilselect_object = {
        attr_num : '_num',
        $select_op_item : null,
        item_all:null,
        item_count : 1,
        left_load_count : 0,
        curr_data :{},
        top_screen_height : function($this){
            return $this.offset().top - $(window).scrollTop();
        },
        select_num_change : function($this, op){
            var _this = this
            var attr_name = $this.parent().parent().parent().data("attr");
            var index = $this.parent().parent().data("row_id");
            var $input_obj = $this.parent().find('#'+ _this.generate_name_num(index));
            if (!$input_obj.length){
                return;
            }
            var value_num = $input_obj.val();
            if (op == '-' || op == '--'){
                value_num--;
            } else if(op == '+' || op == '++'){
                value_num++;
            }
            
            $input_obj.val(value_num);
        },
        select_item_count:function(){
            // include hidden item so you should reduce 1
            //var count = $('.ty-mutilselect-box').find('.ty-mutilselect-item').length - 2;
            return this.item_count;
        },
        generate_name :function(index){
            var _this = this;
            // name index from 1 as front
            if (!index) {
                //index = _this.select_item_count()+1;
                index = _this.select_item_count();
            }
            
            return $('.ty-mutilselect-box').data('attr')+'-'+ (index );
        },
        generate_name_num : function(index)
        {
            var _this = this;
            if (!index) {
                //index = _this.select_item_count()+1;
                index = _this.select_item_count();
            }
            
            return $('.ty-mutilselect-box').data('attr')+'-'+ (index ) + '_num';
        },
        replace_item_name:function(html)
        {
            var _this = this
            html = html.replace(/{{select_title_id}}/ig, _this.generate_name());
            html = html.replace(/{{select_title_num}}/ig, _this.generate_name_num());
            html = html.replace(/{{select_title_row_id}}/ig, _this.select_item_count());
            return html;
        },
        assgin_to_item : function($panel_item)
        {
            var item_id = $panel_item.data("id");
            var item_text = $panel_item.text();
            if (! this.$select_op_item) {
                return;
            }

            $input = this.$select_op_item.find(".ty-mutilselect-item-title");
            $input.data("id", item_id);
            $input.val(item_text);
        },
        num_change_event : function($num_obj, reverse){
            $item = $num_obj.parent().parent().parent();
            $box = $item.parent();
            var id = $item.find('.ty-mutilselect-item-title').data("id") || 0;
            var num =  $num_obj.val();
            if (!id || !num) {
                return;
            }
            if (!ty_mutilselect_object.curr_data[$box.data("attr")]){
                ty_mutilselect_object.curr_data[$box.data("attr")] = {}
            }
            
            var sub_data = ty_mutilselect_object.curr_data[$box.data("attr")];
            //正向 加操作
            if (!reverse){
                sub_data[$item.data('row_id')] = {id:  id, at:num};
            } else {
                // 反向删除 减法操作
                sub_data[$item.data('row_id')] = undefined;
                
            }  
            $box.find('#'+$box.data("attr")).val(JSON.stringify(sub_data)); 
            
        },
        panel_item_load:function($panel, value){
            $ul =  $panel.find('ul');
            $ul.html('');
            var count = 0;
            for(var i in this.item_all){
                var tmp_data = this.item_all[i];
                if (tmp_data.name && tmp_data.name.indexOf(value) >= 0){
                    $ul.append('<li class="ty-mutilselect-item-panel-item" data-id="'+tmp_data.id+'" >'+tmp_data.name+'</li>');
                }
                // 默认空值最多显示10条
                if (!value && count > 10){
                    break;
                }
                count++;
            }
        },
        load_from_data: function($box)
        {
            var _this = this;
            var $data_obj = $box.find('#'+$box.data("attr"));
            console.log($data_obj.val());
            if (!$data_obj.val()){
                return ;
            }
            var arr_item_data = JSON.parse($data_obj.val());
            var arr_item_cache = {}
            for( var i in arr_item_data)
            {   
                var tmp_data = arr_item_data[i];
                // 创建元素，
                var $itemAddAct = $box.find('.ty-mutilselect-item-add');
                var $item_hidden = $box.children(".ty-mutilselect-item-hidden");
                $itemAddAct.parent().before(ty_mutilselect_object.replace_item_name($item_hidden.html()));
                _this.item_count++;
                // 刚创建的元素
                var $item = $itemAddAct.parent().prev();

                var $input = $item.find('.ty-mutilselect-item-title');
                if (_this.item_all[tmp_data["id"]]){
                    $input.val(_this.item_all[tmp_data["id"]]["name"]);
                    $input.data("id", tmp_data["id"]);

                    $num = $item.find('.ty-mutilselect-item-num');
                    $num.val(tmp_data["at"]);
                }else{
                    console.log("the item not found", JSON.stringify(tmp_data));
                }
                // 组织当前有效缓存数据
                arr_item_cache[$item.data("row_id")] = tmp_data;
            }
            // 刷当前有效数据
            ty_mutilselect_object.curr_data[$box.data("attr")] = arr_item_cache;
            $data_obj.val(JSON.stringify( arr_item_cache));
        },
        load_api:function(call_back, test_virtual_api_response, offset){
            // load api data (load ajax api data)
            var _this = this;
            if (test_virtual_api_response || !$('.ty-mutilselect-box').data("action_api")){
                _this.item_all = test_virtual_api_response;
                call_back();
                return;
            }
            var success_callback = function(response_data, http_code){
      
                var data = response_data.data || {};
                _this.left_load_count = _this.left_load_count || response_data.count;
                _this.left_load_count -= Object.keys(data).length;

                _this.item_all = Object.assign(_this.item_all, data);
                var offset = response_data.count - _this.left_load_count
                
                console.log('load api length ' +  _this.left_load_count+ ' data count:' + Object.keys(data).length);
                if (_this.left_load_count > 0 && Object.keys(data).length) {
                    _this.load_api(call_back, test_virtual_api_response, offset);
                } else {
                    call_back();
                }
            }
            var error_callback = function (response_data){
                alert("api of ty_mutilselect compent error: request action api. sys:" + response_data.error)
            }

            $.ajax({
                type: 'GET',
                url: $('.ty-mutilselect-box').data("action_api") + '?offset=' + offset,
                data: {},
                success: success_callback,
                error: error_callback,
                dataType: 'JSON'
            });
            
        },
        load_many:function()
        {
            //var _this = this; // 失效 this 是windows 了  应该是回调导致的
            
            //load _from data 复数
            $('.ty-mutilselect-box').each(function(i, obj){
                ty_mutilselect_object.load_from_data($(this));
                
            });
        },
        load:function(param)
        {
            this.item_all = new Object;
            this.left_load_count = 0;
            
            this.load_api(this.load_many, param, 0);
        }
    };

    //ty_mutilselect_object.load( {"1232":{"id":1232,"at":"1110","name":"test1"},"2000":{"id":2000,"at":"1110","name":"test2"},"3000":{"id":3000,"at":10,"name":"da"}} );
    ty_mutilselect_object.load();

    $('body').on('click','.ty-mutilselect-item-add', function(){
        var $parentbox = $(this).parent().parent();
        var $item = $parentbox.children(".ty-mutilselect-item-hidden");
        $(this).parent().before(ty_mutilselect_object.replace_item_name($item.html()));
        ty_mutilselect_object.item_count++;
    });
    $('.ty-mutilselect-box').on('click','.ty-mutilselect-item-step-del',function(){
        ty_mutilselect_object.select_num_change($(this), '-');
        ty_mutilselect_object.num_change_event($(this).parent().find('.ty-mutilselect-item-num'));
    });
    $('.ty-mutilselect-box').on('click','.ty-mutilselect-item-step-add',function(){
        
        ty_mutilselect_object.select_num_change($(this), '+');
        ty_mutilselect_object.num_change_event($(this).parent().find('.ty-mutilselect-item-num'));
    });
    $('.ty-mutilselect-box').on('click', '.ty-mutilselect-item-del', function(){
        ty_mutilselect_object.num_change_event($(this).parent().find('.ty-mutilselect-item-num'), true)
        $(this).parent().remove();
        ty_mutilselect_object.item_count--;
    });
    $('.ty-mutilselect-box').on('keyup', '.ty-mutilselect-item-title', function(){
        $item = $(this).parent().parent().parent().parent().parent();
        $box = $item.parent();
        $panel = $box.find('.ty-mutilselect-item-panel');
        var position = $(this).offset();
        console.log("cur input position offset ", position.top)
        if (ty_mutilselect_object.top_screen_height($(this)) <400) {
            var top_panel_px = position.top + 40;
            $panel.css({"display":"list-item"});
            $panel.offset({"top":top_panel_px,"left":position.left});
        }else{
            var top_panel_px = position.top - $panel.height();
            $panel.css({"display":"list-item"});
            //top_panel_px = $panel.offset().top - top_panel_px;
            $panel.offset({"left":position.left,"top":top_panel_px});
        }
        // 定位panel 
       
        // 组织pannel 元素
        ty_mutilselect_object.panel_item_load($panel, $(this).val());

        console.log("panel position top", $panel.offset().top, "offset.bottom:",$panel.offset().bottom)
        ty_mutilselect_object.$select_op_item = $item
    });

    $('.ty-mutilselect-box').on('click', '.ty-mutilselect-item-panel-item', function(){
        $panel = $(this).parent().parent();
        $panel.css({"display":"none"});
        ty_mutilselect_object.assgin_to_item($(this));
        
        ty_mutilselect_object.num_change_event(ty_mutilselect_object.$select_op_item.find('.ty-mutilselect-item-num'));
    });

    $('.ty-mutilselect-box').on('input propertychange change', '.ty-mutilselect-item-num', function(){
        ty_mutilselect_object.num_change_event($(this));
    });
});